import axios from 'axios'
import store from '@/global/store'
import global from '@/global/global'

var ip = global.ip

const getLearned = () => {
  // console.log('Into us.js.getLearned : ')
  const { user } = store.getters || {}
  return new Promise((resolve, reject) => {
    if (!user._id) return reject(new Error('user not login'))
    var http = axios.create({
      baseURL: '^/api',
      timeout: 3000,
      headers: { 'Content-Type': 'application/json' }
    })
    let url = '/api/getlearned'
    http.post(ip + url, {
      userName: user.username
    })
      .then(res => {
        // console.log('outof us.js.getLearned : ')
        // console.log(res)
        resolve(res)
      })
      .catch(err => reject(err))
  })
}

const getRevised = () => {
  // console.log('Into us.js.getRevised')
  const { user } = store.getters || {}
  return new Promise((resolve, reject) => {
    if (!user._id) return reject(new Error('user not login'))
    var http = axios.create({
      baseURL: '^/api',
      timeout: 3000,
      headers: { 'Content-Type': 'application/json' }
    })
    let url = '/api/getrevised'
    http.post(ip + url, {
      userName: user.username
    })
      .then(res => {
        resolve(res)
      })
      .catch(err => reject(err))
  })
}

const sendLearned = (en, period, stage, updatedAt, zh) => {
  // console.log('Into sendLearned:')
  const { user } = store.getters || {}
  // console.log(user.username)
  var http = axios.create({
    baseURL: '^/api',
    timeout: 3000,
    headers: { 'Content-Type': 'application/json' }
  })
  let url = '/api/recordlearned'
  http.post(ip + url, {
    userName: user.username,
    en: en,
    period: period,
    stage: stage,
    updatedAt: updatedAt,
    zh: zh
  })
    .then(response => {
      // console.log('Ok us.js.sendLearned : ')
      // console.log(response.data)
    })
    .catch(error => {
      console.log('Error:', error)
      if (error.response) {
        console.log('Response data:', error.response.data)
      }
    })
}

const sendRevised = (listname, startedAt, location, updatedAt) => {
  console.log('into us.js.sendRevised---location to be sended')
  console.log(location)
  const { user } = store.getters || {}
  var http = axios.create({
    baseURL: '^/api',
    timeout: 3000,
    headers: { 'Content-Type': 'application/json' }
  })
  // console.log('Into  sendRevise:')
  let url = '/api/recordrevised'
  http.post(ip + url, {
    userName: user.username,
    listName: listname,
    startedAt: startedAt,
    location: location,
    updatedAt: updatedAt
  })
    .then(response => {
      // console.log('OK us.js.sendRevised : ')
      // console.log(response.data)
    })
    .catch(error => {
      console.log('Error:', error)
      if (error.response) {
        console.log('Response data:', error.response.data)
      }
    })
}

const editLearned = (userId, wordObj, { update = true, period = 0, stage = 0, periodChange = 0, stageChange = 0 }) => {
  return new Promise((resolve, reject) => {
    // console.log('Into us.js.editLearned')

    const { wordEn, wordZh } = wordObj || {}
    if (!wordEn || !wordZh) return reject(new Error('word object incorrect'))

    getLearned().then((learn) => {
      var learned = JSON.parse(JSON.stringify(learn.data))
      let findFlag = false
      if (learned) { // 用户有学习记录
        if (learned && learned[wordEn]) { // 用户学过该单词
          console.log('用户学过该单词')
          findFlag = true
          // 改后端learned表
          sendLearned(wordEn, period || learned[wordEn].period + periodChange, stage || learned[wordEn].stage + stageChange, update ? Date.now() : learned[wordEn].updatedAt, wordZh)
        } else { // 用户没学过该单词
          console.log('用户没学过该单词')
          // 改后端learned表
          sendLearned(wordEn, period || 1, stage || 7, Date.now(), wordZh)
        }

        if (findFlag) {
          console.log('word status updated')
          resolve('update')
        } else {
          console.log('new word added to learned')
          resolve('add')
        }
      } else { // 用户没有学习记录
        // 改后端learned表
        sendLearned(wordEn, period || 1, stage || 7, Date.now(), wordZh)
          .then((res) => console.log(res))
        console.log('new learned record created')
        resolve('new')
      }
    })
  })
}

const editRevised = (userId, listName, { location = 0, change = 0 }) => {
  // console.log('Into us.editRevised')
  return new Promise((resolve, reject) => {
    getRevised().then((revise) => {
      let progress = JSON.parse(JSON.stringify(revise.data))
      let findFlag = false
      if (progress) {
        if (progress && progress[listName]) { // 找到了该list
          // console.log('找到了该list')
          findFlag = true
          sendRevised(listName, progress[listName].startedAt, location || progress[listName].location + change, Date.now())
        } else {
          // 未找到该list
          // console.log('未找到该list')
          sendRevised(listName, Date.now(), location + change, Date.now())
        }

        if (findFlag) {
          // console.log('list progress edited')
          resolve('update')
        } else {
          // console.log('new list added to progress')
          resolve('add')
        }
      } else { // 该用户的progress暂未建立记录
        sendRevised(listName, location + change, Date.now(), Date.now())
          .then((res) => console.log(res))
        // console.log('new progress record created')
        resolve('new')
      }
    })
  })
}

const us = {
  getLearned, // 获取learned表
  getRevised,
  sendLearned,
  sendRevised, // (listname, startedAt, location, updatedAt) =>
  editLearned, // 根据用户操作修改用户learned表并发给后端保存
  editRevised
}

export default us
